package biznussoft.fieldservice360.dialogfragments;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.Calendar;

import android.app.Activity;
import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import biznussoft.fieldservice360.R;
import biznussoft.fieldservice360.listeners.GlobalListener;
import biznussoft.fieldservice360.utils.Base64;
import biznussoft.fieldservice360.utils.View.Signature;

import com.salesforce.androidsdk.rest.RestClient;

public class SignaturetDialogFragmen  extends DialogFragment{
	private LinearLayout mContent;
	private Signature mSignature;
	private Button  mGetSign;
	public static String tempDir;
	public int count = 1;
	public String current = null;
	private Bitmap mBitmap;
	private View mView;
	private File mypath;
	private String[] fileList = null;
	private GlobalListener listener;
	private RestClient client;
	private String uniqueId;
	private String args[];
	private Dialog  dialog;
	 public static DialogFragment newInstace() {
	        DialogFragment dialogFragment = new SignaturetDialogFragmen();
	        return dialogFragment;
	    }
	 
	 @Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		listener = (GlobalListener) getActivity();
	}
	 
	
	 
	    @Override
	    public Dialog onCreateDialog(Bundle savedInstanceState) {
	    	
	    	 dialog = new Dialog(getActivity());
	         dialog.setTitle("Fieldservice 360");
	         dialog.setContentView(R.layout.signature_fragment);
	         dialog.show();
	         tempDir =  Environment.getExternalStoragePublicDirectory("download")+"/canvas/";
	         prepareDirectory();
	 		uniqueId = getTodaysDate() + "_" + getCurrentTime() + "_"
	 				+ Math.random();
	 		current = uniqueId + ".png";
	 		mypath = new File(tempDir, current);

	 		mContent = (LinearLayout) dialog.findViewById(R.id.linearLayout);
	 		mSignature = new Signature(getActivity(), null);
	 		mSignature.setBackgroundColor(Color.WHITE);
	 		mContent.addView(mSignature, LayoutParams.FILL_PARENT,
	 				LayoutParams.FILL_PARENT);
	 		mGetSign = (Button) dialog.findViewById(R.id.getsign);
//	 		mGetSign.setEnabled(false);
	 		mView = mContent;



	 		mGetSign.setOnClickListener(new OnClickListener() {
	 			@SuppressWarnings("static-access")
				public void onClick(View v) {
	 				Log.v("log_tag", "Panel Saved");
	 					mView.setDrawingCacheEnabled(true);
	 					mSignature.save(mView, mContent, mypath, getActivity());
	 					/*Bundle b = new Bundle();
	 					b.putString("status", "done");*/
	 					File videoFiles = new File(tempDir);
	 			        if (videoFiles.isDirectory()) {
	 			            fileList = videoFiles.list();
	 			        }
	 			        Log.i("NCS","IMAGE path is :"+fileList[0]);
	 			        File imageFile = new File(tempDir,fileList[0]);
	 			    	Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
	 			    	ByteArrayOutputStream stream = new ByteArrayOutputStream();
	 			    	bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
	 			    	byte[] image = stream.toByteArray();             
	 			    	String img_str = Base64.encodeBytes(image);      
	 			    	Log.i("NCS","String iss :"+img_str);
	 			    	listener.getSignature(img_str);
	 			    	dialog.dismiss();
	 			    	
	 			    	/*imageString(img_str); +im
	 			    	finish();*/
	 			    	/*Intent intent = new Intent();
	 					intent.putExtra("base64String",img_str);  
	 					getActivity().setResult(getActivity().RESULT_OK, intent);
	 					getActivity().finish();*/
//	 				}
	 			}
	 		});

	         
	         
	        
	       /*  Button cancel = (Button) dialog.findViewById(R.id.btCancel);
	         cancel.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					
					dialog.dismiss();
				}
			});*/
	         
	        
	    
	        return dialog;
	    }
	    
	    private boolean prepareDirectory() {
			try {
				if (makedirs()) {
					return true;
				} else {
					return false;
				}
			} catch (Exception e) {
				Log.i("NCS","Exception is  :"+e.getMessage());
				/*Toast.makeText(
						this,
						"Could not initiate File System.. Is Sdcard mounted properly?",
						1000).show();*/
				return false;
			}
		}
	    private boolean makedirs() {
			File tempdir = new File(tempDir);
			if (!tempdir.exists())
				tempdir.mkdirs();

			if (tempdir.isDirectory()) {
				File[] files = tempdir.listFiles();
				for (File file : files) {
					if (!file.delete()) {
						System.out.println("Failed to delete " + file);
					}
				}
			}
			return (tempdir.isDirectory());
		}
	    private String getTodaysDate() {

			final Calendar c = Calendar.getInstance();
			int todaysDate = (c.get(Calendar.YEAR) * 10000)
					+ ((c.get(Calendar.MONTH) + 1) * 100)
					+ (c.get(Calendar.DAY_OF_MONTH));
			Log.w("DATE:", String.valueOf(todaysDate));
			return (String.valueOf(todaysDate));

		}

		private String getCurrentTime() {

			final Calendar c = Calendar.getInstance();
			int currentTime = (c.get(Calendar.HOUR_OF_DAY) * 10000)
					+ (c.get(Calendar.MINUTE) * 100) + (c.get(Calendar.SECOND));
			Log.w("TIME:", String.valueOf(currentTime));
			return (String.valueOf(currentTime));

		}

	 
	    
}
